<template>
  <div class="container">
    <div class="container-content">
      <vab-query-form>
        <vab-query-form-top-panel v-show="data.showSearch">
          <el-form
            ref="queryRef"
            :model="tableOptions.queryForm"
            :inline="true"
            label-width="10"
            label-suffix=""
            style="padding-right: 10px"
            @keyup.enter="queryTableData"
          >
            <el-form-item prop="initiatorId" label="" v-if="!props.mine">
              <CommonSelect
                v-model:defaultValue="tableOptions.queryForm.initiatorId"
                :placeholder="translate('flow.inst.initiatorId')"
                label="userName"
                value="id"
                url="/admin/user/get/list"
              />
            </el-form-item>
            <el-form-item prop="flowKey">
              <el-input
                v-model="tableOptions.queryForm.flowKey"
                placeholder="请输入流程key"
              />
            </el-form-item>
            <el-form-item prop="status">
              <DictSelect
                v-model:defaultValue="tableOptions.queryForm.status"
                placeholder="请选择工单运行状态"
                dict-code="order_run_status"
                show-all="Y"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                icon="Refresh"
                type="warning"
                @click="handleResetQuery"
                >{{ translate("buttons.reset") }}</el-button
              >
              <el-button icon="search" type="primary" @click="queryTableData">
                {{ translate("buttons.search") }}
              </el-button>
            </el-form-item>
          </el-form>
        </vab-query-form-top-panel>
        <vab-query-form-left-panel>
          <el-button icon="remove" type="primary" @click="handleDelete([])"
            >删除</el-button
          >
        </vab-query-form-left-panel>
        <vab-query-form-right-panel>
          <RightToolBar
            v-model:showSearch="data.showSearch"
            :export="false"
            @export="exportExcel"
            @refresh="queryTableData"
            @toggle="handleToggleSearch"
          />
        </vab-query-form-right-panel>
      </vab-query-form>

      <el-table
        ref="tableRef"
        v-loading="tableOptions.loading"
        border
        :data="tableOptions.dataList"
        :cell-style="tableStyle.cellStyle"
        :header-cell-style="tableStyle.headerCellStyle"
        :height="tableOptions.height"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="handleSortChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" label="序号" width="55" />
        <el-table-column
          prop="icon"
          label="图标"
          show-overflow-tooltip
          width="60"
        >
          <template #default="scope">
            <IconifyIconOnline
              v-if="scope.row.defFlow && scope.row.defFlow.icon"
              :icon="scope.row.defFlow.icon.name"
              :style="{
                background: scope.row.defFlow.icon.bgc,
                color: scope.row.defFlow.icon.color
              }"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="orderInstCode"
          label="工单名称"
          show-overflow-tooltip
          width="150"
        >
          <template #default="scope">
            {{ scope.row.flowOrder ? scope.row.flowOrder.orderName : "" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="orderInstCode"
          label="工单编号"
          show-overflow-tooltip
          width="200"
        />
        <el-table-column
          prop="flowKey"
          label="流程Key"
          show-overflow-tooltip
          width="140"
        />
        <el-table-column
          prop="statusDesc"
          label="工单状态"
          show-overflow-tooltip
          width="120"
        >
          <template #default="scope">
            {{ scope.row.statusDesc }}
            <el-button
              v-if="
                scope.row.status === '-2' &&
                scope.row.defFlow &&
                scope.row.defFlow.status === '1'
              "
              type="primary"
              @click.stop="handleStartOrder(scope.row)"
            >
              发起
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="flowInstId"
          label="流程实例"
          show-overflow-tooltip
          width="180"
        />
        <el-table-column
          prop="flowStatusDesc"
          label="流程状态"
          show-overflow-tooltip
          width="100"
        >
          <template #default="scope">
            {{ scope.row.runFlow ? scope.row.runFlow.flowStatusDesc : "" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="ini"
          label="发起人"
          show-overflow-tooltip
          width="100"
        >
          <template #default="scope">
            {{ scope.row.runFlow ? scope.row.runFlow.initiatorName : "" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="runNodeName"
          label="当前节点"
          show-overflow-tooltip
          width="100"
        >
          <template #default="scope">
            {{ scope.row.runNodeName }}
          </template>
        </el-table-column>
        <el-table-column
          prop="finishTime"
          label="完成时间"
          show-overflow-tooltip
          width="160"
        />
        <el-table-column
          prop="groupName"
          label="分组"
          show-overflow-tooltip
          width="120"
        >
          <template #default="scope">
            {{ scope.row.flowOrder ? scope.row.flowOrder.groupName : "" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="formName"
          label="表单"
          show-overflow-tooltip
          width="120"
        >
          <template #default="scope">
            {{ scope.row.flowForm ? scope.row.flowForm.formName : "" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="version"
          label="流程版本号"
          show-overflow-tooltip
          width="100"
        >
          <template #default="scope">
            {{ scope.row.defFlow ? scope.row.defFlow.version : "" }}
          </template>
        </el-table-column>
        <el-table-column
          prop="createUserName"
          label="创建人"
          show-overflow-tooltip
          width="120"
        />
        <el-table-column
          prop="createTime"
          label="创建时间"
          show-overflow-tooltip
          width="160"
        />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: space-between;
              "
            >
              <el-dropdown>
                <el-button icon="ArrowDown" text type="primary">
                  功能
                  <arrow-down />
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="handleViewForm(scope.row, 'view')"
                      >查看</el-dropdown-item
                    >
                    <el-dropdown-item
                      v-if="
                        scope.row.status === '-2' || scope.row.status === '-3'
                      "
                      divided
                      @click="handleViewForm(scope.row, 'edit')"
                    >
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="scope.row.flowInstId && scope.row.status != '-2'"
                      divided
                      @click="handleViewComment(scope.row)"
                      >审批过程</el-dropdown-item
                    >
                    <el-dropdown-item
                      v-if="scope.row.status === '-1'"
                      divided
                      @click="handleRecallReset(scope.row)"
                    >
                      撤回申请
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="scope.row.status === '-3'"
                      divided
                      @click="handleRecallReset(scope.row)"
                    >
                      重启流程
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="scope.row.status === '-1'"
                      divided
                      @click="handleStopFlow(scope.row)"
                      >提前结束申请</el-dropdown-item
                    >
                    <el-dropdown-item
                      v-if="scope.row.status === '-1'"
                      divided
                      @click="handleCancelFlow(scope.row)"
                      >作废申请</el-dropdown-item
                    >
                    <el-dropdown-item
                      v-if="scope.row.status === '-2'"
                      divided
                      @click="handleDelete([scope.row.id])"
                    >
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-button
                icon="view"
                text
                type="primary"
                @click="openViewFlowPhoto(scope.row)"
                >流程图</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page="tableOptions.pagination.current"
        :layout="tableOptions.pagination.layout"
        :page-size="tableOptions.pagination.size"
        :total="tableOptions.pagination.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
      <el-dialog
        v-model="data.showStartForm"
        width="70%"
        top="5vh"
        title="发起工单"
        append-to-body
      >
        <StartForm
          :order="data.orderInst"
          :form="data.form"
          :readonly="false"
          :dialog="true"
          @close="data.showStartForm = false"
          @started="
            data.showStartForm = false;
            queryTableData();
          "
          @saved="data.showStartForm = false"
        />
      </el-dialog>
      <CommonDialog
        v-model="data.showFlowForm"
        width="70%"
        :title="flowFormTitle"
        append-to-body
        :show-footer="false"
      >
        <FlowForm
          :orderInstId="data.orderInst.id"
          :readonly="data.form.operType === 'view'"
          :dialog="true"
          @close="data.showFlowForm = false"
          @saved="data.showFlowForm = false"
          @started="data.showFlowForm = false"
        />
      </CommonDialog>
      <CommonDialog
        v-if="data.showComment"
        v-model="data.showComment"
        width="60%"
        title="审批过程"
        append-to-body
        :show-footer="false"
      >
        <CommentTimeLine
          v-if="data.showComment"
          :id="data.orderInst.id"
          :flow-inst-id="data.orderInst.flowInstId"
          @close="data.showComment = false"
        />
      </CommonDialog>
      <CommonDialog
        v-model="data.showFlowPic"
        width="60%"
        title="流程图"
        append-to-body
        :show-footer="true"
        :showFooterOk="false"
        cancelText="关闭"
        @cancel="data.showFlowPic = false"
        @closed="data.showFlowPic = false"
      >
        <FlowPhoto
          v-if="data.showFlowPic"
          :def-flow-id="data.orderInst.defFlowId"
          :flow-inst-id="data.orderInst.flowInstId"
          @close="data.showFlowPic = false"
        />
      </CommonDialog>
    </div>
  </div>
</template>

<script setup lang="ts" name="TaskOrderInstMine">
import { BasicTableProps, useTable } from "@/hooks/table";
import { queryPage, delObjs } from "@/api/flow/orderinst";
import { useMessage, useMessageBox } from "@/hooks/message";
import { translate } from "@/plugins/i18n";
import { cloneObject } from "@/utils/common";
import * as runFlowApi from "@/api/flow/runflow";
import DictSelect from "@/components/dictSelect.vue";
import CommonSelect from "@/components/commonSelect.vue";
import RightToolBar from "@/components/rightToolBar.vue";
import StartForm from "../order/startForm.vue";
// 引入组件
const FlowPhoto = defineAsyncComponent(
  () => import("@/components/flow/flowPhoto.vue")
);
const FlowForm = defineAsyncComponent(
  () => import("@/components/flow/flowForm.vue")
);
const CommentTimeLine = defineAsyncComponent(
  () => import("@/components/flow/flowCommentTimeline.vue")
);

const $message = useMessage();
const queryRef = ref();
const tableRef = ref(null);
const route = useRoute();

const props = defineProps({
  mine: {
    type: Boolean,
    default: true
  }
});

const data = reactive({
  showSearch: true,
  showFlowPic: false,
  showFlowForm: false,
  showStartForm: false,
  showComment: false,
  orderInst: {
    id: "",
    orderId: "",
    defFlowId: "",
    flowInstId: "",
    orderInstCode: "",
    flowKey: "",
    formId: "",
    operType: ""
  },
  form: {
    id: "",
    formName: "",
    formInfo: null,
    printInfo: null,
    componentUrl: "",
    operType: ""
  }
});

const tableOptions: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {
    mine: props.mine,
    initiatorId: "",
    flowKey: "",
    status: "ALL",
    flowStatus: "ALL"
  },
  autoLoad: true,
  queryFunction: queryPage,
  descs: ["create_time"]
});

const {
  instance: instTable,
  tableStyle,
  queryTableData,
  handleSelectionChange,
  handleResetQuery,
  handleRowClick,
  handleSizeChange,
  handleCurrentChange,
  handleSortChange,
  downBlobFile,
  handleToggleHeight
} = useTable(tableOptions, tableRef);

const handleToggleSearch = () => {
  if (data.showSearch) {
    handleToggleHeight();
  } else {
    handleToggleHeight(-40);
  }
};

// 导出excel
const exportExcel = () => {
  downBlobFile(
    "/esflow/order/run/export",
    tableOptions.queryForm,
    "order-run.xlsx"
  );
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  await useMessageBox()
    .confirm("此操作将永久删除")
    .then(async () => {
      try {
        if (ids.length === 0 && instTable.dataSelections.length > 0) {
          ids.push(...instTable.dataSelections.map(n => n.id as string));
        }
        if (ids && ids.length > 0) {
          await delObjs(ids.join(",")).then(res => {
            if (res.code === 200) {
              queryTableData();
              useMessage().success("删除成功");
            } else {
              useMessage().error(res.msg);
            }
          });
        }
      } catch (err: any) {
        useMessage().error(err.msg);
      }
    });
};

const flowFormTitle = computed(() => {
  let title = "查看工单";
  if (data.form.operType === "edit") {
    title = "编辑工单";
  } else if (data.form.operType === "copy") {
    title = "复制工单";
  }
  return title;
});

const initDataOrder = item => {
  data.orderInst.id = item.id;
  data.orderInst.orderId = item.orderId;
  data.orderInst.defFlowId = item.defFlowId;
  data.orderInst.flowKey = item.flowKey;
  data.orderInst.formId = item.formId;
  data.orderInst.orderInstCode = item.orderInstCode;
  if (item.flowForm) {
    data.form.id = item.flowForm.id;
    data.form.formName = item.flowForm.formName;
    data.form.formInfo = item.flowForm.formInfo;
    data.form.printInfo = item.flowForm.printInfo;
    data.form.componentUrl = item.flowForm.componentUrl;
  }
};

const handleStartOrder = async item => {
  if (!item) {
    data.showStartForm = false;
    return;
  }
  initDataOrder(item);
  data.showStartForm = true;
};

const handleViewForm = (row: any, operType: string) => {
  cloneObject(data.orderInst, row);
  data.form = Object.assign(data.form, {}, row.flowForm);
  if (data.form) {
    data.form.operType = operType;
    data.showFlowForm = true;
  }
};

const handleViewComment = row => {
  cloneObject(data.orderInst, row);
  data.showComment = true;
};

function openViewFlowPhoto(row) {
  let rowFlowInstId = row.flowInstId;
  //暂存
  if (row.status === "-2") {
    rowFlowInstId = null;
  }
  cloneObject(data.orderInst, row);
  data.showFlowPic = true;
}

function handleRecallReset(row) {
  //工单状态 -3 撤回
  const flag = row.status === "-1" ? "recall" : "reset";
  const params = { id: row.flowInstId, flowKey: row.flowKey, flag: flag };
  if (flag === "reset") {
    //重发
    runFlowApi.recallReset(params).then(res => {
      if (res.code === 200) {
        useMessage().success("重启成功");
        queryTableData();
      } else {
        useMessage().error(res.msg);
      }
    });
    return;
  }
  useMessageBox()
    .confirm("是否确认要撤回该工单?")
    .then(() => {
      runFlowApi.recallReset(params).then(res => {
        if (res.code === 200) {
          useMessage().success("撤回成功");
          queryTableData();
        } else {
          useMessage().error(res.msg);
        }
      });
    });
}

// 提前结束流程
function handleStopFlow(row) {
  useMessageBox()
    .prompt("请输入提前结束流程理由")
    .then(({ value }) => {
      const obj = { id: row.flowInstId, reason: value };
      runFlowApi.stopFlow(obj).then(res => {
        if (res.code === 200) {
          useMessage().success("操作成功");
          queryTableData();
        } else {
          useMessage().error(res.msg);
        }
      });
    });
}
// 作废流程
function handleCancelFlow(row) {
  useMessageBox()
    .prompt("请输入作废理由")
    .then(({ value }) => {
      const obj = {
        id: row.flowInstId,
        reason: value,
        flag: "0"
      };
      runFlowApi.cancelFlow(obj).then(res => {
        if (res.code === 200) {
          useMessage().success("操作成功");
          queryTableData();
        } else {
          useMessage().error(res.msg);
        }
      });
    });
}
</script>
